package com.example.hosptialtag.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import javax.servlet.http.HttpSession;

/**
 * @Author liuyuhao&caiang
 * @Date 2022/2/21
 */

@Service
public class DoctorService {
    @Autowired
    private final JdbcTemplate jdbcTemplate;
    public DoctorService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    public String loginDoctor(String name, String password, Model model, HttpSession session) {
        try {
            if (name.length() == 0 || password.length() == 0) {
                model.addAttribute("msgLogin", "所有空不允许为空");
                return "login";
            }
            int num = jdbcTemplate.queryForObject("select count(*) from tb_doctor where name = ?", Integer.class, name);
            if (num == 0) {
                model.addAttribute("msgLogin", "账号不存在");
                return "login";
            } else {
                int passwordCheck = jdbcTemplate.queryForObject("select count(*) from tb_doctor " +
                        "where name = ? and password = ?", Integer.class, name, password);
                if (passwordCheck == 1) {
                    session.setAttribute("doctor",jdbcTemplate.queryForMap("select * from tb_doctor where name = ? and password = ?", name, password));
                    session.setAttribute("doctorVO",jdbcTemplate.queryForMap("select name, o.description as office, r.description as role from tb_doctor d left join tb_offices o on d.oid = o.id left join tb_role r on d.role = r.id where d.name = ? and d.password = ?", name, password));
                    return "forward:main";// 成功
                } else {
                    model.addAttribute("msgLogin", "账号密码不匹配");
                    return "login";
                }
            }
        }catch (Exception e) {
            model.addAttribute("msgLogin", "数据库连接出错");
            return "login";
        }
    }

}
